package com.zzg.test2.web

import android.content.Context
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.RenderProcessGoneDetail
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.FrameLayout
import androidx.activity.OnBackPressedCallback
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import com.leadbank.baselbf.log.LogBus
import com.zzg.test2.R
import com.zzg.test2.manager.CacheManager
import com.zzg.test2.manager.CacheWebLoadManager
import com.zzg.test2.manager.WebViewCacheManager
import java.io.File
import java.io.FileInputStream
import java.io.InputStream


class WebFragment : Fragment() {
    private val TAG = "WebFragment"
    private lateinit var webView: WebView
    private var url: String = ""
    private val cacheManager by lazy { context?.let { WebViewCacheManager(it) } }
//    private var userAgentString: String = ""

    companion object {
        fun newInstance(url: String): WebFragment {
            val fragment = WebFragment()
            val args = Bundle()
            args.putString("url", url)
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            url = it.getString("url", "")
        }
        CacheManager.init(requireContext()) // 初始化缓存管理器
        requireActivity().onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if (!::webView.isInitialized || webView == null) {
                    requireActivity().onBackPressed() // 调用系统默认行为
                }

                if (webView.canGoBack()) {
                    webView.goBack()
                } else {
                    activity!!.finish()
                    return@handleOnBackPressed
                }
            }
        })
    }

    var frameLayout: FrameLayout? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_web, container, false)
        frameLayout = view.findViewById(R.id.web_frameLayout)
        webView = WebView(requireContext())
//        webView = createHuaweiWebView(requireContext())
        frameLayout!!.addView(webView)
        WebSetting.setWebSetting(webView)
        setWebClient()
//        userAgentString =  webView.settings.userAgentString
        webView.loadUrl(url)
        return view
    }
    private fun createHuaweiWebView(context: Context): WebView {
        return if (isHuaweiDevice() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            try {
                val huaweiWebViewClass = Class.forName("com.huawei.webkit.WebView")
                val constructor = huaweiWebViewClass.getConstructor(Context::class.java)
                constructor.newInstance(context) as WebView
            } catch (e: Exception) {
                WebView(context)
            }
        } else {
            WebView(context)
        }
    }


    private fun isHuaweiDevice(): Boolean {
        return try {
            Class.forName("com.huawei.android.webkit.WebViewProvider")
            true
        } catch (e: ClassNotFoundException) {
            Build.MANUFACTURER.equals("HUAWEI", ignoreCase = true) ||
                    Build.BRAND.equals("HUAWEI", ignoreCase = true)
        }
    }
    private fun setWebClient() {
        webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                url?.let { view?.loadUrl(it) }
                LogBus.d(TAG, "shouldOverrideUrlLoading: $url")
                return true
            }

            override fun onReceivedError(
                view: WebView?,
                request: WebResourceRequest?,
                error: WebResourceError?
            ) {
                super.onReceivedError(view, request, error)
            }

            override fun onReceivedHttpError(
                view: WebView?,
                request: WebResourceRequest?,
                errorResponse: WebResourceResponse?
            ) {
                super.onReceivedHttpError(view, request, errorResponse)
            }

            @RequiresApi(Build.VERSION_CODES.O)
            override fun onRenderProcessGone(view: WebView?, detail: RenderProcessGoneDetail?): Boolean {
                if (view == webView) {
                    if (detail!!.didCrash()) {
                        // 渲染进程崩溃（例如由于内存访问违规等）
                       LogBus.d(TAG, "渲染进程因内部错误崩溃");
                        // 可以在这里上报崩溃日志
                    } else {
                        // 渲染进程被系统杀死（通常是由于内存不足）
                       LogBus.d(TAG, "渲染进程被系统杀死");
                    }
                   LogBus.d(TAG, "崩溃了，——————Render process crashed, reloading..."+detail.toString())
                    handleWebViewCrash()
                    return true
                }
                return false
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
               LogBus.d(TAG, "加载完成  onPageFinished")
            }




//            override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {
//                val url = request?.url.toString()
//               LogBus.d(TAG, "shouldInterceptRequest request = $url")
//
//                // 检查缓存
//                CacheManager.get(url)?.let {
//                    LogBus.d(TAG, "Cache hit for $url")
//                    return it
//                }
//
//                // 没有缓存，发起网络请求
//                try {
//                    val urlConnection = URL(url).openConnection()
//                    urlConnection.setRequestProperty("User-Agent", webView.settings.userAgentString)
//                     val userAgent = webView.settings.userAgentString
//                    LogBus.d(TAG, "webView.settings.userAgentString: ${userAgent}")
////                    LogBus.d(TAG, "userAgentString: $userAgentString")
//                    urlConnection.setRequestProperty("User-Agent", userAgent)
//                    val inputStream = urlConnection.getInputStream()
//
//                    // 保存到缓存
//                    CacheManager.put(url, inputStream)
//
//                    // 重新获取缓存响应
//                    return CacheManager.get(url)
//                } catch (e: Exception) {
//                    LogBus.d(TAG, e.printStackTrace())
//                   LogBus.d(TAG, "Error loading resource: $url")
//                    return super.shouldInterceptRequest(view, request)
//                }
//            }


            override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest): WebResourceResponse? {
                val url = request.url.toString()

                // 只处理JS文件
                if (url.endsWith(".js")) {
                    try {
                        // 首先尝试从缓存获取
                        val instance = CacheWebLoadManager.getInstance()
                        val cachedFile: File = instance.getCachedFile(context,url)
                        return if (cachedFile.exists()) {
                            // 找到缓存，直接返回
                            LogBus.d(TAG, "找到缓存，"+cachedFile+"直接返回 Cache hit for url = $url")
                            val inputStream: InputStream = FileInputStream(cachedFile)
                            WebResourceResponse("application/javascript", "utf-8", inputStream)
                        } else {
                            // 没有缓存，从网络下载
                            LogBus.d(TAG, "没有缓存，从网络下载 url = $url")
                            if (!instance.isDownloading(url)) {
                                instance.setDownloading(url, true)
                                instance.downloadAndCacheAsync(context,webView,url)
                            }
                            // 返回空，WebView会继续原始请求
                            null
                        }
                    } catch (e: java.lang.Exception) {
                        e.printStackTrace()
                    }
                }

                // 对于非JS文件，不进行特殊处理
                return null
            }


//            override fun shouldInterceptRequest(
//                view: WebView,
//                request: WebResourceRequest
//            ): WebResourceResponse? {
//                return cacheManager!!.getCachedResource(request.url.toString())
//            }
        }
    }

//    private fun getMimeType(url: String): String {
//        return CacheManager.getMimeType(url)
//    }

    private fun handleWebViewCrash() {
        try {
            if (::webView.isInitialized) {
                webView.destroy()
            }
            webView = WebView(requireContext())
            frameLayout!!.addView(webView)
            webView.loadUrl(url)
        } catch (e: Exception) {
           LogBus.d("TabWebJsFragment", "Error handling WebView crash")
            LogBus.d("TabWebJsFragment",  e.printStackTrace())
        }
    }
//    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
//        super.setUserVisibleHint(isVisibleToUser)
//
//        if (view != null) {
//            if (isVisibleToUser) {
//                // Fragment对用户可见，加载网页
//                if (url != null && webView.url.isNullOrEmpty()) {
//                    webView.loadUrl(url)
//                }
//            } else {
//                // Fragment不可见，释放WebView资源
//                webView.stopLoading()
//                webView.clearCache(true)
////                webView.onPause()
//            }
//        }
//    }
    override fun onResume() {
        super.onResume()
        webView.resumeTimers()
        webView.onResume()
    }

    override fun onPause() {
        super.onPause()
        webView.onPause()
        webView.pauseTimers()
    }

    override fun onDestroyView() {
        webView.destroy()
        super.onDestroyView()
    }
}